using server.Services;
using server.Extensions;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.IO;

async void RunWebApp(string[] args)
{

    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddCors(op=>{
        op.AddDefaultPolicy(policy=>{
            policy.WithOrigins("*");
        });
    });
    builder.Services.AddControllers()
        .AddJsonOptions(op =>
        {
            op.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        });
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    builder.Services.AddDbContext<LibraryContext>();
    // builder.Services.AddSingleton<IEncryptService, MD5Encrypt>();
    // builder.Services.AddSingleton<TokenService,TokenService>();
    builder.Services.AddSingleton<TokenService>();

    var app = builder.Build();


    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger(options => options.SerializeAsV2 = true);
        app.UseSwaggerUI();
    }

    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseCors();
    // app.UseAuthentication();
    // app.UseAuthorization();
    app.MapControllers();

    using (var scope = app.Services.CreateScope())
    {
        var created = scope.ServiceProvider.GetRequiredService<LibraryContext>().Database.EnsureCreated();
        if (created)
        {
            System.Console.WriteLine("New database created!");
            await Seed();
        }
    }
    var url= app.Configuration.GetValue<string>("Url","http://localhost:8000");
    System.Console.WriteLine("Read listen url: "+url);
    app.Run(url);

}
if (args.Contains("seed"))
{
    await Seed();
}else{
    RunWebApp(args);
}

async Task Seed()
{
    var config= new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();
    System.Console.WriteLine("Seeding Data...");
    var super_password=config.GetValue<string>("Seed:Super","123456");    
    var db = new LibraryContext();
    var seed = new Seed(db);
    await seed.SeedRole();
    System.Console.WriteLine("Seed roles done!");
    await seed.SeedSuper(super_password);
    System.Console.WriteLine("Seed super user with password:"+super_password);
    System.Console.WriteLine("Seeding Data completed!");
}